﻿using System;
using Csla.Xaml;
using Microsoft.Practices.Prism.Regions;
using BizControl.Presentation.Infrastructure.Controls;
using Microsoft.Practices.Prism;
using System.ComponentModel.Composition;
using BizControl.Presentation.Infrastructure.Constants;
using System.ComponentModel;
using Microsoft.Practices.Prism.Commands;
using BizControl.Presentation.Infrastructure.Helpers;
using System.Collections.Generic;
using BizControl.Library;
using BizControl.Library.BusinessObjects.Models;
using System.Windows;
using System.Windows.Input;
using BizControl.Library.BusinessObjects.People;
using Microsoft.Win32;
using System.IO;
using System.Data.Linq;
using BizControl.Library.Security;
using Csla;

namespace BizControl.Presentation.PersonEditModule.ViewModels
{
  [Export]
  [PartCreationPolicy(CreationPolicy.NonShared)]
  public class PersonEditViewModel : ViewModel<PersonBO>, INavigationAware, IConfirmNavigationRequest, IHeaderInfoProvider<string>
  {
    private IRegionManager _regionManager;

    private readonly DelegateCommand _closeCommand;
    private readonly DelegateCommand _loadPhotoCommand;

    [ImportingConstructor]
    public PersonEditViewModel(IRegionManager regionManager)
    {
      _regionManager = regionManager;
      _loadPhotoCommand = new DelegateCommand(LoadPhoto);
      _closeCommand = new DelegateCommand(Close);
    }

    private void Refresh()
    {
      DoRefresh(GetPerson);
    }

    PersonBO GetPerson()
    {
      return _person;
    }

    #region Handlers

    private void LoadPhoto()
    {
      if (null != Model)
      {
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.Multiselect = false;
        ofd.DefaultExt = ".jpg";
        ofd.Filter = "JPEG Files (*.jpg;*.jpeg)|*.jpg;*.jpeg";
        if (ofd.ShowDialog() ?? false)
        {
          try
          {
            Model.Photo = null;
            Model.Photo = new Binary(File.ReadAllBytes(ofd.FileName));
          }
          catch (Exception)
          {
            MessageBox.Show("Open file exception");
          }
        }
      }
    }

    private void Close()
    {
      _regionManager.RequestNavigate(ShellRegionNames.MainContentRegion, ViewNames.PeopleViewName, NavigationCompleted);
    }

    private void NavigationCompleted(NavigationResult result)
    {
      // confirmation
    }

    #endregion

    #region Properties

    public ICommand LoadPhotoCommand
    {
      get { return _loadPhotoCommand; }
    }

    public ICommand CloseCommand
    {
      get { return _closeCommand; }
    }

    private PersonBO _person;
    private PersonBO Person
    {
      get { return _person; }
      set
      {
        if (_person != value)
        {
          _person = value;
          Refresh();
        }
      }
    }

    #endregion

    #region INavigationAware Members

    public Guid Id { get; set; }
    public bool Initialized { get; set; }

    private void Initialize(Guid id)
    {
      Id = id;
      Initialized = true;
    }

    public bool IsNavigationTarget(NavigationContext navigationContext)
    {
      string personId = navigationContext.Parameters[NavigationParametersNames.IdName];
      if (!string.IsNullOrEmpty(personId))
      {
        Guid id = Guid.Parse(personId);
        if (Initialized && Id == id)
        {
          return true;
        }
        else if (!Initialized)
        {
          Initialize(id);
          return true;
        }
      }
      return false;
    }

    public void OnNavigatedFrom(NavigationContext navigationContext)
    {
    }

    public void OnNavigatedTo(NavigationContext navigationContext)
    {
      string personId = navigationContext.Parameters[NavigationParametersNames.IdName];
      string newPerson = navigationContext.Parameters[NavigationParametersNames.NewPersonName];
      if (!string.IsNullOrEmpty(personId))
      {
        if (Model == null)
        {
          Guid id = Guid.Parse(personId);
          Person = PersonBO.GetPerson(id);
          Initialize(id);
        }
      }
      else if (!string.IsNullOrEmpty(newPerson))
      {
        Person = PersonBO.NewPerson();
        Initialize(Person.PersonId);
      }
    }

    #endregion

    #region IConfirmNavigationRequest Members

    public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
    {
      ConfirmationHelper.ConfirmNavigationRequestSaveDlg<PersonBO>(this, continuationCallback);
    }

    #endregion

    #region IHeaderInfoProvider<string> Members

    public string HeaderInfo
    {
      get { return BizControl.Presentation.PersonEditModule.Properties.Resources.PersonEditHeaderInfo; }
    }

    #endregion
  }
}
